package com.jy.adscm.operation.pebase.controller;


import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.base.bean.TaskManagerAttchment;
import com.jy.adscm.operation.pebase.bean.PeDocument;
import com.jy.adscm.operation.pebase.bean.QueryPeDocument;
import com.jy.adscm.operation.pebase.service.PeDocumentService;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.support.SimpleCoreResponse;
import com.jy.adscm.system.utils.AdscmSystemUtils;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyl
 * @since 2019-04-10
 */
@RestController
@RequestMapping("/adscm/pebase/peDocument")
public class PeDocumentController {
    @Autowired
    RedisTemplate<Object, Token> tokenRedisTemplate;
    @Autowired
    PeDocumentService peDocumentService;
    @Value("${pebase.upload-path}")
    private  String annexUploadPath;//附件上传路径
    @RequestMapping("insert")
    public SimpleCoreResponse insert( HttpServletRequest request) throws AdscmSystemException , IOException {
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        String peDocumentstr = request.getParameter("peDocument");
        if (peDocumentstr==null||"".equals(peDocumentstr)){
            throw  new AdscmSystemException("peDocumentstr 没得");
        }
        ObjectMapper mapper = new ObjectMapper();
        PeDocument peDocument = mapper.readValue(peDocumentstr, PeDocument.class);
        List<String> paths = null;
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            String path = annexUploadPath /*+ File.separator*/ + UUID.randomUUID().toString().replaceAll("-","") + File.separator;

            paths = AdscmSystemUtils.getInstance().uploadFileNoNewName(multiRequest,path);
        }
        if (paths!=null){
            String path = paths.get(0);
            peDocument.setPath(path);
            String  fileName =  path.substring(path.lastIndexOf("\\") + 1);
            peDocument.setFileName(fileName);
            peDocument.setCreator(token.getUser().getId().toString());
            peDocument.setCreateTime(new Date());
        }
        //查询当日最大编码
        String  yearMonth=new SimpleDateFormat("yyyyMMdd").format(new Date());
        String code="";
        Wrapper<PeDocument> peDocumentWrapper =new EntityWrapper<>();
        peDocumentWrapper.like("code",yearMonth, SqlLike.RIGHT);
        peDocumentWrapper.orderBy("code",false);
        List<PeDocument> peDocuments = peDocumentService.selectList(peDocumentWrapper);
         if (peDocuments!=null&&peDocuments.size()>0){
             PeDocument peDocument1 = peDocuments.get(0);
             String code1 = peDocument1.getCode();
             Long temp= Long.valueOf(code1)+1;
             code=String.valueOf( temp)  ;
         }else {
             code=yearMonth+"0001";
         }
        peDocument.setCode(code);
        boolean insert = peDocumentService.insert(peDocument);
        return new SimpleCoreResponse("200","新增成功",insert);
    }

    @RequestMapping("delete/{id}")
    public SimpleCoreResponse delete(@PathVariable Integer id , HttpServletRequest request)throws AdscmSystemException {
        boolean result =false;
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
       PeDocument peDocument = peDocumentService.selectById(id);
        if (  peDocument.getCreator().equals(token.getUser().getId().toString())){
            result=  peDocumentService.deleteById(id);
        }
        return new  SimpleCoreResponse("200","删除成功",result);
    }
    @RequestMapping("update")
    public SimpleCoreResponse update(@RequestBody PeDocument peDocument, HttpServletRequest request) throws AdscmSystemException{
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        peDocument.setCreator(token.getUser().getId().toString());
        peDocument.setCreateTime(new Date());
        Boolean result = peDocumentService.updateById(peDocument);
        return  new SimpleCoreResponse("200","修改成功",result);
    }
    @RequestMapping("selectByDid")
    public SimpleCoreResponse select(@RequestBody QueryPeDocument queryPeDocument, HttpServletRequest request) throws AdscmSystemException{
        Page<PeDocument> page =new Page<>(queryPeDocument.getCurrentPage(),queryPeDocument.getPageSize());
        page= peDocumentService.selectPeDocument(page,queryPeDocument);
        return  new SimpleCoreResponse("200","查询成功",page);
    }
    @RequestMapping("download/{id}")
    public  SimpleCoreResponse downloadSjAttachment(@PathVariable String id, HttpServletRequest request, HttpServletResponse response)throws AdscmSystemException {
        PeDocument peDocument = peDocumentService.selectById(id);
        if (peDocument==null){
            throw  new AdscmSystemException("没找到文件");
        }
        AdscmSystemUtils.getInstance().downloadFile(peDocument.getPath(),response);
        return new SimpleCoreResponse("200","下载成功",null);
    }
}

